package com.xrit.service;

import com.xrit.sunnyday.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户真实的信息
        User user = findByUsername(username);
        //GrantedAuthority:权限和角色的公共接口
        List<GrantedAuthority> authorities = new ArrayList<>();
        //将信息给到GrantedAuthority
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(authority);
        authority = new SimpleGrantedAuthority("add");
        authorities.add(authority);
        //将拿到用户名和密码给security
        org.springframework.security.core.userdetails.User user1 =
                new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
        return user1;
    }

    /**
     * 模拟从数据库查询User的信息，用户名，密码，角色，权限
     */
    public User findByUsername(String name){
        if ("peng".equals(name)){
            //如果和admin匹配代表有这个用户，我们自己造一些模拟数据
            User user = new User();
            user.setUsername("peng");
            user.setPassword("$2a$10$4e5UfQJWnv74QEHkoRAH/esoj5fNdp2Zs6LPMFeeATV47AJSHmNj6");
            return user;
        }
        return null;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //加密
        String encode = bCryptPasswordEncoder.encode("1234");
        System.out.println(encode);
        //$2a$10$4e5UfQJWnv74QEHkoRAH/esoj5fNdp2Zs6LPMFeeATV47AJSHmNj6
        //$2a$10$ptjjHgh.ZEJHyIReGU9l0ugq7Py/0X5ZWH8pa/ebHBVcGUUDz8SWa
        //$2a$10$IqVD7vedVQbv6LqsqIcqXeyXmKwwS5DMVG8AVuptfxi/kqWFhvi82
    }
}
